//
//  HBDiscoverItemExtraCell.m
//  HeartBeat
//
//  Created by karong on 2023/8/24.
//

#import "HBDiscoverItemExtraCell.h"
#import "HBChannelItemModel.h"

@interface HBDiscoverItemExtraCell () <CAAnimationDelegate>
@property (weak, nonatomic) IBOutlet UIView *broadcastView;
@property (weak, nonatomic) IBOutlet UILabel *broadcastLabel;
@property (nonatomic, strong) CATransition *transition;
@property (nonatomic, assign) BOOL isAnimation;
@property (nonatomic, strong) NSArray * dataArray;
@property (nonatomic, assign) NSInteger userIndex;
@property (nonatomic, strong) HBItemModel * item;
@end

@implementation HBDiscoverItemExtraCell

- (void)setDataWithObject:(NSArray *)broadcastList {
    self.broadcastView.hidden = NO;
    self.dataArray = broadcastList;
    self.transition = nil;
    self.isAnimation = NO;
    [self trasitionRewardUserView];
}
- (IBAction)btnAction:(id)sender {
    if ([self.delegate respondsToSelector:@selector(discoverItemExtraCellBtnAction:)]) {
        [self.delegate discoverItemExtraCellBtnAction:self.item];
    }
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (flag) {
        double delayInSeconds = 1.0;
        WeakSelf;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            self.isAnimation = NO;
            [weakSelf trasitionRewardUserView];
        });
    }
}

- (void)trasitionRewardUserView {
    if (self.dataArray.count == 0) {
        return;
    }
    if (self.isAnimation) {
        return;
    }
    if (self.dataArray.count <= self.userIndex) {
        self.userIndex = 0;
    }
    HBItemModel * item = self.dataArray[self.userIndex];
    self.item = item;
    self.broadcastLabel.text = item.title;
    if (self.dataArray.count > 1) {
        self.isAnimation = YES;
        [self.broadcastLabel.layer addAnimation:self.transition forKey:nil];
        self.userIndex ++;
    }
}

- (CATransition *)transition {
    if (!_transition) {
        //- 创建一个转场动画:
        _transition = [CATransition animation];
        _transition.repeatCount = 1;
        //    - 确定动画类型:
        _transition.type = @"cube";
        //    - 确定子类型(方向等)
        _transition.subtype = kCATransitionFromTop;
        //    - 确定动画时间
        _transition.duration = 1;
        _transition.delegate = self;
    }
    return _transition;
}

@end
